package com.zyf.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/** 全局过滤器 gateway 网关用户认证过滤器
 * @author zyf
 * @date 2021年05月19日 10:34
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        //内部访问接口，不允许外部访问
        if (antPathMatcher.match("/**/inner/**",path)){
            ServerHttpResponse response = exchange.getResponse();
            return out(response, ResultCodeEnum.PERMISSION);
        }
        Long userId = this.getUserId(request);
        //api接口，异步请求，校验用户必须登录
        if(antPathMatcher.match("/api/**/auth/**",path)){
            if (StringUtils.isEmpty(userId)){
                ServerHttpResponse response = exchange.getResponse();
                return out(response,ResultCodeEnum.LOGIN_AUTH);
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * api接口鉴权失败返回数据
     * @author zyf
     * @date 2021/5/19 10:51
     * @param response
     * @param resultCodeEnum
     * @return reactor.core.publisher.Mono<java.lang.Void>
     */
    private Mono<Void> out(ServerHttpResponse response, ResultCodeEnum resultCodeEnum){
        Result result = Result.build(null,resultCodeEnum);
        byte[] bytes = JSONObject.toJSONString(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码，否则在浏览器中乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 获取当前用户的id
     * @author zyf
     * @date 2021/5/19 10:57
     * @param request
     * @return java.lang.Long
     */
    private Long getUserId(ServerHttpRequest request){
        String token = "";
        List<String> tokenList = request.getHeaders().get("token");
        if(null != tokenList){
            token = tokenList.get(0);
        }
        if (!StringUtils.isEmpty(token)){
            return JwtHelper.getUserId(token);
        }
        return null;
    }
}
